var page = {};
//页面窗口
page.window=$.extend(page.window,{
	width:$(window).width(),
	height:$(window).height(),
	grid:{
	  width:$(window).width(),
	  height:$(window).height()-120,
	  halfHeight:($(window).height()-240)/2,
	  height8:($(window).height()-240)*0.8,
	  height7:($(window).height()-240)*0.7,
	  height6:($(window).height()-240)*0.6,
	  height4:($(window).height()-240)*0.4,
	  height3:($(window).height()-240)*0.3,
	  height2:($(window).height()-240)*0.2,
	  buttonHeight:120
	}
});
//通用JS
$(document).ready(function(){
	//加载页面
	if(page.pageInit)page.pageInit();
	//高度只适应
	$(window).resize(function() {
		setIframeHeight($("#iframe_content")[0]);
	});
});

//高度只适应
function setIframeHeight(iframe){
	if (iframe) {
		iframe.height=document.documentElement.clientHeight - 96;
	}
}


/**
 * 显示遮罩层
 * @returns
 */
function showLoadmask(){
	var loadmaskId = layer.load(1, {
		shade: [0.3,'#000'] //0.1透明度的白色背景
	});
	return loadmaskId;
}
/**
 * 关闭遮罩层，如果有id关闭指定id的
 * @param maskId
 */
function closeLoadmask(maskId){
	if(maskId){
		layer.close(maskId);
	}else{
		layer.closeAll('loading');
	}
}


/**
 * 通用方法
 * */
(function ($) {
    /**
     * 拓展全局静态方法
     */
    $.extend({
    	   /**submit**/
         dataSubmit :function(id,url,successfun,errorfun){
         	//打开遮罩
        	showLoadmask();
         	$('#'+id).form('submit', {
        		url : url,
        		onSubmit : function(data) {

        		},
        		success : function(rs) {
	            	//关闭遮罩
	    			closeLoadmask();
	               	if(successfun)successfun(rs); 
        		},
        		error : function(rs){
        			//关闭遮罩
	    			closeLoadmask();
                	if(errorfun)errorfun(rs)
                	
        		},complete: function(XMLHttpRequest, textStatus, xhr) {
        	        var oauthstatus = XMLHttpRequest.getResponseHeader("oauthstatus");
        	        if(oauthstatus == '401'){
        	        	 window.location.href = contextPath + "/view.htm";
        	            return;
        	        }
        	    }
        	});
         },
    	/** 异步Post **/
          dataPost: function (url, data, successfun, errorfun) {
        	//打开遮罩
        	showLoadmask();
            $.ajax({
                async: true,
                type: 'POST',
                url: url,
                data: data,
                dataType: "json",
                success: function(rs){
                	//关闭遮罩
	    			closeLoadmask();
                	if(successfun)successfun(rs);
                },
                error:function(rs){
                	//关闭遮罩
	    			closeLoadmask();
                	if(errorfun){
                		errorfun(rs);
                	}else{
                		if(successfun)successfun({success:false,msg:"系统错误,请联系管理员."});
                	}
                },complete: function(XMLHttpRequest, textStatus, xhr) {
        	        var oauthstatus = XMLHttpRequest.getResponseHeader("oauthstatus");
        	        if(oauthstatus == '401'){
        	        	 window.location.href = contextPath + "/view.htm";
        	            return;
        	        }
        	    }
            });
        },
        /** 异步Post **/
        dataPostJson: function (url, data, success, errorfun) {
        	//打开遮罩
        	showLoadmask();
            $.ajax({
                async: true,
                type: 'POST',
                url: url,
                data: data,
                dataType: "json",
    			contentType: "application/json", 
                success: function(rs){
                	//关闭遮罩
	    			closeLoadmask();
                	if(success)success(rs);
                },
                error:function(rs){
                	//关闭遮罩
	    			closeLoadmask();
                	if(errorfun){
                		errorfun(rs);
                	}else{
                		if(success)success({success:false,msg:"系统错误,请联系管理员."});
                	}
                },complete: function(XMLHttpRequest, textStatus, xhr) {
        	        var oauthstatus = XMLHttpRequest.getResponseHeader("oauthstatus");
        	        if(oauthstatus == '401'){
        	        	 window.location.href = contextPath + "/view.htm";
        	            return;
        	        }
        	    }
            });
        }, 
        /** 异步Post **/
        dataPostArray: function (url, data, success, errorfun) {
        	//打开遮罩
        	showLoadmask();
            $.ajax({
                async: true,
                type: 'POST',
                url: url,
                data: data,
                dataType: "json",
			    traditional: true,  
                success: function(rs){
                	//关闭遮罩
	    			closeLoadmask();
                	if(success)success(rs);
                },
                error:function(rs){
                	//关闭遮罩
	    			closeLoadmask();
                	if(errorfun){
                		errorfun(rs);
                	}else{
                		if(success)success({success:false,msg:"系统错误,请联系管理员."});
                	}
                },complete: function(XMLHttpRequest, textStatus, xhr) {
        	        var oauthstatus = XMLHttpRequest.getResponseHeader("oauthstatus");
        	        if(oauthstatus == '401'){
        	        	 window.location.href = contextPath + "/view.htm";
        	            return;
        	        }
        	    }
            });
        }, 
        /** 同步Post **/
        dataSyncPost: function (url, data, success, errorfun) {
        	//打开遮罩
        	showLoadmask();
            $.ajax({
                async: false,
                type: 'POST',
                url: url,
                data: data,
                dataType: "json",
                success: function(rs){
                	//关闭遮罩
	    			closeLoadmask();
                	if(success)success(rs);
                },
                error:function(rs){
                	//关闭遮罩
	    			closeLoadmask();
                	if(errorfun){
                		errorfun(rs);
                	}else{
                		if(successfun)successfun({success:false,msg:"系统错误,请联系管理员."});
                	}
                },complete: function(XMLHttpRequest, textStatus, xhr) {
        	        var oauthstatus = XMLHttpRequest.getResponseHeader("oauthstatus");
        	        if(oauthstatus == '401'){
        	        	 self.location.href = basePath + "/view.htm";
        	            return;
        	        }
        	    }
            });
        },
        /** 同步Post **/
        dataSyncPostJson: function (url, data, success, errorfun) {
        	//打开遮罩
        	showLoadmask();
            $.ajax({
                async: false,
                type: 'POST',
                url: url,
                data: data,
                dataType: "json",
    			contentType: "application/json", 
                success: function(rs){
                	//关闭遮罩
	    			closeLoadmask();
                	if(success)success(rs);
                },
                error:function(rs){
                	//关闭遮罩
	    			closeLoadmask();
                	if(errorfun){
                		errorfun(rs);
                	}else{
                		if(success)success({success:false,msg:"系统错误,请联系管理员."});
                	}
                },complete: function(XMLHttpRequest, textStatus, xhr) {
        	        var oauthstatus = XMLHttpRequest.getResponseHeader("oauthstatus");
        	        if(oauthstatus == '401'){
        	        	 window.location.href = contextPath + "/view.htm";
        	            return;
        	        }
        	    }
            });
        },
        /** 同步Post **/
        syncPost: function (url, data, success) {
            $.ajax({
                async: false,
                type: 'POST',
                url: url,
                data: data,
                success: function(rs){
                	if(success)success(rs);
                },
                error:function(){
                    if(success)success({success:false,msg:"系统错误,请联系管理员."});
                },complete: function(XMLHttpRequest, textStatus, xhr) {
        	        var oauthstatus = XMLHttpRequest.getResponseHeader("oauthstatus");
        	        if(oauthstatus == '401'){
        	        	 window.location.href = contextPath + "/view.htm";
        	            return;
        	        }
        	    },
                dataType: "json"
            });
        },
        /** traditionalPost **/
        tradPost: function (url, data, success) {
            $.ajax({
                async: true,
                type: 'POST',
                traditional: true,  
                url: url,
                data: data,
                success: function(rs){
                	//关闭遮罩
	    			closeLoadmask();
                	if(success)success(rs);
                },
                error:function(){
                	//关闭遮罩
	    			closeLoadmask();
                	if(success)success({success:false,msg:"系统错误,请联系管理员."});
                },complete: function(XMLHttpRequest, textStatus, xhr) {
        	        var oauthstatus = XMLHttpRequest.getResponseHeader("oauthstatus");
        	        if(oauthstatus == '401'){
        	        	 window.location.href = contextPath + "/view.htm";
        	            return;
        	        }
        	    },
                dataType: "json"
            });
        },
        /** traditional同步 **/
        tradNotPost: function (url, data, success) {
            $.ajax({
                async: false,
                type: 'POST',
                traditional: true,  
                url: url,
                data: data,
                success: function(rs){
                	//关闭遮罩
	    			closeLoadmask();
                	if(success)success(rs);
                },
                error:function(){
                	//关闭遮罩
	    			closeLoadmask();
                	if(success)success({success:false,msg:"系统错误,请联系管理员."});
                },complete: function(XMLHttpRequest, textStatus, xhr) {
        	        var oauthstatus = XMLHttpRequest.getResponseHeader("oauthstatus");
        	        if(oauthstatus == '401'){
        	        	 window.location.href = contextPath + "/view.htm";
        	            return;
        	        }
        	    },
                dataType: "json"
            });
        },
        /** 同步获取JSON **/
        syncGetJson: function (url, success) {
            $.ajax({
                async: false,
                type: 'GET',
                url: url,
                success: function(rs){
                	if(success)success(rs);
                },
                error:function(){
                	if(success)success({success:false,msg:"系统错误,请联系管理员."});
                },complete: function(XMLHttpRequest, textStatus, xhr) {
        	        var oauthstatus = XMLHttpRequest.getResponseHeader("oauthstatus");
        	        if(oauthstatus == '401'){
        	        	 window.location.href = contextPath + "/view.htm";
        	            return;
        	        }
        	    },
                dataType: "json"
            });
        },
        /** Html转义 **/
        encodeHtml: function (s) {
            return (typeof s != "string") ? s :
                s.replace(/"|&|'|<|>|[\x00-\x20]|[\x7F-\xFF]|[\u0100-\u2700]/g,
                    function ($0) {
                        var c = $0.charCodeAt(0), r = ["&#"];
                        c = (c == 0x20) ? 0xA0 : c;
                        r.push(c);
                        r.push(";");
                        return r.join("");
                    });
        },
        /** 获取URL参数 **/
        getUrlPara: function (name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]); return;
        },
        /** 获取URL QueryString **/
        getUrlParas: function () {
        	var url = location.href;
        	if(url.indexOf("?") == -1){
        		return;
        	}
        	return url.substring(url.indexOf("?")+1,url.length); 
        },
        /** 获取Form参数对象-用于Post请求 **/
        getFormParasObj: function (form) {
        	var o = {};
    		$.each(form.serializeArray(), function(index) {
    			if (o[this['name']]) {
    				o[this['name']] = o[this['name']] + "," + this['value'];
    			} else {
    				o[this['name']] = this['value'];
    			}
    		});
    		return o;
        },
        /** 获取Form参数字符-用于get请求 **/
        getFormParasStr: function (form) {
        	var o = "";
        	$.each(form.serializeArray(), function(index) {
        		var key = this['name'], val = this['value'];
        		if(val && val.length > 0){
        			o = o + key + "=" + val + "&";        			
        		}
        	});
        	return o.substring(0, o.length-1); 
        },
        /** 获取浏览器类型 **/
        getBrowser: function() {
        	var explorer = window.navigator.userAgent;
			if (explorer.indexOf("MSIE") >= 0) {
				return 'ie';
			} else if (explorer.indexOf("Firefox") >= 0) {
				return 'firefox';
			} else if (explorer.indexOf("Chrome") >= 0) {
				return 'chrome';
			} else if (explorer.indexOf("Opera") >= 0) {
				return 'opera';
			} else if (explorer.indexOf("Safari") >= 0) {
				return 'safari';
			}
        },
        //表单重置
        formReset:function(form){
        	$.each($(form).find("input[type=text]"),function(index,field){
        		var id = $(field).attr("id");
        		if(id)$("#"+id).val("")
        		else {
        			var name = $(field).attr("name").substring(7);
        				if($("#"+name).hasClass("datetimebox-f")){
        		 	    	$("#"+name).datetimebox("setValue","");
        		 	    }else if($("#"+name).hasClass("datebox-f")){
        			 	    	$("#"+name).datebox("setValue","");
        		 	    }else if($("#"+name).hasClass("combobox-f")){
        		 	    	$("#"+name).combobox("setValue","");
        		 	    }else{
        		 	    	$("#"+name).textbox("setValue","");
        		 	    }
        		}
        	});
        }
    });
})(jQuery);

//弹出层
var showWindow = function(name,url,params,callback,hiddenBtn){
	  var layerParams = {
			  type:1 
      		  ,title: name
      		  ,area: [(page.window.width)+'px', (page.window.height)+'px']
      		 // ,shade: 0
      		  ,maxmin: false
      		 // ,content: msg
      		  ,scrollbar:true
      		  ,btn: ['保存', '关闭'] //只是为了演示
      		  ,yes: function(index){
      			  if(top.page.form){
      				top.page.form.event.submit(top.layer,callback,index);
      			  }
      		  }
      		  ,cancal: function(index){
      			top.layer.close(index);
      		  }
      		  ,zIndex: 800 //重点1
      		  ,success: function(layero,index){
      			if(top.page.form && top.page.form.init){
      				top.page.form.init(callback,top.layer,index);
      			}
      		  }
	  }
	  if(hiddenBtn){
		  layerParams.btn = null; 
	  }
	 $.ajax({
	        url: url,
	        global: false,
	        type: "POST",
	        dataType: "html",
	        data:params,
	        async: false,
	        success: function(msg) {
	        	layerParams.content = msg;
	        top.layer.open(layerParams);
	        }
	    })
	    //keydown
	    $("body").keydown(function(e){
	    	 if(e.keyCode == 13){
	    		 return false;
	    	 }
	    });
}

//弹出层
var openWindow = function(name,url,params,callback){
	 $.ajax({
	        url: url,
	        global: false,
	        type: "POST",
	        dataType: "html",
	        data:params,
	        async: false,
	        success: function(msg) {
	        layer.open({
	      		  type: 2 
	      		  ,title: name
	      		  ,area: [(page.window.width)*0.7+'px', (page.window.height*0.7)+'px']
	      		 // ,shade: 0
	      		  ,maxmin: false
	      		  ,content: msg
	      		  ,scrollbar:true
	      		  ,btn: ['保存', '关闭'] //只是为了演示
	      		  ,yes: function(index){
	      			  if(page.form){
	      				page.form.event.submit(layer,callback,index);
	      			  }
	      		  }
	      		  ,cancal: function(index){
	      		    layer.close(index);
	      		  }
	      		  ,zIndex: 800 //重点1
	      		  ,success: function(layero,index){
	      			if(page.form && page.form.init){
	      				page.form.init(callback,layer,index);
	      			}
	      		  }
	      		});
	        }
	    })
}
/**
 * 打开窗口
 */
var openIframeWindow = function(name,url,params,callback,hiddenBtn){
	  layer.open({
  		  type: 2 
  		  ,title: name
  		  ,area: [(page.window.width)*0.8+'px', (page.window.height*0.8)+'px']
  		 // ,shade: 0
  		  ,maxmin: false
  		  ,content: url
  		  ,scrollbar:true
  		  ,btn: !hiddenBtn?['保存', '关闭']:null
  		  ,yes: function(index){
  			  var iframe = window["layui-layer-iframe"+index];
  			  if(iframe.page.form){
  				iframe.page.form.event.submit(layer,callback,index);
  			  }
  		  }
  		  ,cancal: function(index){
  		    layer.close(index);
  		  }
  		  ,zIndex: 1800 //重点1
  		  ,success: function(layero,index){
  			var iframe = window["layui-layer-iframe"+index];
  			if(iframe.page.form && iframe.page.form.init){
			  iframe.page.form.init(callback,layer,index);
  			}
  			
  		  }
  		});
}

/**
 * 打开窗口
 */
var showIframeWindow = function(name,url,params,callback,hiddenBtn){
	  top.layer.open({
  		  type: 2 
  		  ,title: name
  		  ,area: [(top.page.window.width)*0.8+'px', (top.page.window.height*0.8)+'px']
  		 // ,shade: 0
  		  ,maxmin: false
  		  ,content: url
  		  ,scrollbar:true
  		  ,btn: !hiddenBtn?['保存', '关闭']:null //只是为了演示
  		  ,yes: function(index){
  			 
  		  var iframe = top.window["layui-layer-iframe"+index];
  			  if(iframe.page.form){
  				iframe.page.form.event.submit(top.layer,callback,index);
  			  }
  		  }
  		  ,cancal: function(index){
  		    top.layer.close(index);
  		  }
  		  ,zIndex: 1800 //重点1
  		  ,success: function(layero,index){
  			var iframe = top.window["layui-layer-iframe"+index];
  			if(iframe.page.form && iframe.page.form.init){
			  iframe.page.form.init(callback,top.layer,index);
  			}
  		  }
  		});
}
/**
 * 获取HTML信息
 */
var LoadHtml = function(url,params,callback){
	 $.ajax({
	        url: url,
	        global: false,
	        type: "POST",
	        dataType: "html",
	        data:params,
	        async: false,
	        success: function(msg) {
	           if(callback)callback(msg);
	        }
	    })
}

/***********验证框架***************/
$.validator.setDefaults({
    /*关闭键盘输入时的实时校验*/
    onkeyup: null,
    /*添加校验成功后的执行函数--修改提示内容，并为正确提示信息添加新的样式(默认是valid)*/
    success: function(label){
        /*label的默认正确样式为valid，需要通过validClass来重置，否则这里添加的其他样式不能被清除*/
        label.text('').addClass('valid');
    },
    /*重写校验元素获得焦点后的执行函数--增加[1.光标移入元素时的帮助提示,2.校验元素的高亮显示]两个功能点*/
    onfocusin: function( element ) {
        
    },
    /*重写校验元素焦点离开时的执行函数--移除[1.添加的帮助提示,2.校验元素的高亮显示]*/
    onfocusout: function( element ) {
    	$(element).removeClass("form-error");
    },
    //重写showErrors
    showErrors: function (errorMap, errorList) {
        var msg = "";
        $.each(errorList, function (i, v) {
            //在此处用了layer的方法,显示效果更美观
            layer.tips(v.message, v.element, {guide:3});
            $(v.element).addClass("form-error");
            return false;
        });  
    },
});


//时间格式化
Date.prototype.Format = function (fmt) { //author: meizz   
    var o = {  
        "M+": this.getMonth() + 1, //月份   
        "d+": this.getDate(), //日   
        "H+": this.getHours(), //小时   
        "m+": this.getMinutes(), //分   
        "s+": this.getSeconds(), //秒   
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度   
        "S": this.getMilliseconds() //毫秒   
    };  
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));  
    for (var k in o)  
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));  
    return fmt;  
}  

/**
 * 时间格式化
 */
function DatFormatter(cellvalue, options, rowObject){
	if(cellvalue){
		return new Date(cellvalue).Format("yyyy-MM-dd HH:mm:ss");
	}
	return "";
}

/**
 * 时间格式化
 */
function NoTimeFormatter(cellvalue, options, rowObject){
	if(cellvalue){
		return new Date(cellvalue).Format("yyyy-MM-dd");
	}
	return "";
}
/**
 * 级联方法
 * @param url
 */
function cascadeConnection(_this,url,childId){
	$(childId).val("");
	$(childId).empty();
	var id = $(_this).val();
	LoadHtml(url,{id:id},function(msg){
	   $(childId).html(msg);
	   //选中第一个
	   $(childId).find("option:eq(0)").attr("selected", 'selected'); 
	   $(childId).change();
	});
}

/**
 * 级联方法 获取下节点内容
 * @param url
 */
function cascadeConnectionText(_this,url,childId,valueId,buyMonth){
	$(childId).val("");
	var id = $(_this).val();
	$.dataPost(url,{id:id},function(result){
	   if(result.success){
		   $(childId).val(result.data[valueId]);
		   $(buyMonth).find("option:eq(0)").attr("selected", 'selected'); 
		   $(buyMonth).change();
	   }
	});
}

function cascadeConnectionPrice(_this,url,childId,valueId,packageId){
	$(childId).val("");
	var value = $(_this).val();
	if(value=="请选择"){
		return ;
	}
	var id=$('#packageId').val();
	$.dataPost(url,{val:value,id:id},function(result){
	   if(result.success){
		   $(childId).val(result.data[valueId]);
		 //选中第一个
		   $(childId).find("option:eq(0)").attr("selected", 'selected'); 
		   $(childId).change();
	   }
	});
}


//数值限定
$("[data-number]").keyup(function(event){
	var patt = ($(this).data("number")+"").split(",");
	var regExpStr = "";//  /-?\d{0,}[.]?\d{0,}/;
	if(event.keyCode < 47 && event.keyCode !=32){
		return ;
	}
	if(patt[0].charAt(0)=="-"){
		regExpStr+="-?";
	}
	if(patt.length==2){
		regExpStr+="\\d{0,"+patt[0].replace("-","")+"}[.]?\\d{0,"+patt[1]+"}";
	}else{
		regExpStr+="\\d{0,"+patt[0].replace("-","")+"}";
	}
	$(this).val($(this).val().match(new RegExp(regExpStr)));
});
